package com.opass.cloud.core.security.oauth2;

import com.opass.cloud.core.security.SecurityUser;
import com.opass.cloud.core.security.SecurityConstants;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fp295
 * @date 2018/4/16
 * 自定义JwtAccessToken转换器
 */
public class CustomJwtAccessTokenEnhancer extends JwtAccessTokenConverter {


    /**
     * 生成token
     *
     * @param accessToken
     * @param authentication
     * @return
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(accessToken);
        final Map<String, Object> additionalInfo = new HashMap<>(8);
        Object principal = authentication.getPrincipal();
        if (principal != null) {
            if (principal instanceof SecurityUser) {
                // 用户信息
                SecurityUser baseUser = (SecurityUser) principal;
                additionalInfo.put(SecurityConstants.OPEN_ID, baseUser.getUserId());
            }
            if (principal instanceof ClientDetails) {
                ClientDetails clientDetails = (ClientDetails) principal;
                additionalInfo.put(SecurityConstants.OPEN_ID, clientDetails.getAdditionalInformation().get("appId"));
            }
        }
        token.setAdditionalInformation(additionalInfo);
        return super.enhance(token, authentication);
    }

    /**
     * 解析token
     *
     * @param value
     * @param map
     * @return
     */
    @Override
    public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) {
        OAuth2AccessToken oauth2AccessToken = super.extractAccessToken(value, map);
        return oauth2AccessToken;
    }
}
